package com.share.tool.devops.service.impl;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.BuildWithDetails;
import com.offbytwo.jenkins.model.ConsoleLog;
import com.offbytwo.jenkins.model.JobWithDetails;
import com.offbytwo.jenkins.model.QueueReference;
import com.share.tool.devops.service.JenkinsService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
@Service
public class JenkinsServiceImpl implements JenkinsService {
    @Autowired
    private static JenkinsServer jenkinsServer;

    @Override
    @ApiOperation("构建任务")
    public String createJob(String projectName, Map<String, String> paramMap) {
        String reStr = null;
        QueueReference build = null;
        try {
            // 执行 build 任务
            JobWithDetails jobWithDetails = jenkinsServer.getJob(projectName);
            if (CollectionUtils.isEmpty(paramMap)) {
                build = jobWithDetails.build();
            } else {
                build = jobWithDetails.build(paramMap);
            }
            reStr = build.getQueueItemUrlPart();
        } catch (Exception e) {
            log.error("执行构建异常", e);
        }
        return reStr;
    }


    @Override
    @ApiOperation("构建任务")
    public String buildJob(String projectName) {
        try {
            jenkinsServer.getJob(projectName).build();
            return "正在构建任务请耐心等待!";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @ApiOperation("构建日志")
    public String buildLog(String projectName) {
        ConsoleLog currentLog = null;
        String currentLoging = null;
        try {
            // 这里用最后一次编译来示例
            BuildWithDetails build = jenkinsServer.getJob(projectName).getLastBuild().details();
            // 当前日志
            currentLog = build.getConsoleOutputText(0);

            // 输出当前获取日志信息
            currentLoging = currentLog.getConsoleLog();
            log.info("输出当前获取日志信息: {}", currentLoging);
        } catch (Exception e) {
            log.info("jenkins 获取正在执行构建任务的日志信息异常", e);
        }
        return currentLoging;
    }
}
